package com.hontech.bv.ui.view

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.Button
import android.widget.FrameLayout
import com.hontech.bv.R
import com.hontech.bv.conn.Device
import com.hontech.bv.conn.Proto
import com.hontech.bv.task.onClick
import com.hontech.bv.ui.window.showErr
import com.hontech.bv.ui.window.showProg
import kotlinx.coroutines.delay

class PingView(ctx: Context, attrs: AttributeSet) : FrameLayout(ctx, attrs) {

    private val btnPipeLine: Button
    private val btnPick: Button
    private val btnArm: Button
    private val btnIce: Button
    private val btnPearl: Button
    private val btnPowder: Button
    private val btnHeat: Button
    private val btnAll: Button

    init {
        val view = LayoutInflater.from(ctx).inflate(R.layout.view_ping, this)
        btnPipeLine = view.findViewById(R.id.id_ping_btn_pipe_line)
        btnPick = view.findViewById(R.id.id_ping_btn_pick)
        btnArm = view.findViewById(R.id.id_ping_btn_arm)
        btnIce = view.findViewById(R.id.id_ping_btn_ice)
        btnPearl = view.findViewById(R.id.id_ping_btn_pearl)
        btnPowder = view.findViewById(R.id.id_ping_btn_powder)
        btnHeat = view.findViewById(R.id.id_ping_btn_heat)
        btnAll = view.findViewById(R.id.id_ping_btn_all)

        btnPipeLine.onClick { pingAny("流水线控制板", Proto.ID_MASTER) }
        btnPick.onClick { pingAny("取物门控制板", Proto.ID_PICK) }
        btnArm.onClick { pingAny("机械手控制板", Proto.ID_ARM) }
        btnIce.onClick { pingAny("制冰机控制板", Proto.ID_ICE) }
        btnPearl.onClick { pingAny("珍珠架控制板", Proto.ID_PEARL) }
        btnPowder.onClick { pingAny("粉料架控制板", Proto.ID_POWDER) }
        btnHeat.onClick { pingAny("加热控制板", Proto.ID_HEAT) }
        btnAll.onClick(::pingAll)
    }

    private suspend fun pingAll() {
        val dialog = showProg("ping所有", "ping流水线控制板")

        try {
            Device.ping(Proto.ID_MASTER)

            dialog.setMsg("ping取物门控制板")
            Device.ping(Proto.ID_PICK)

            dialog.setMsg("ping机械臂控制板")
            Device.ping(Proto.ID_ARM)

            dialog.setMsg("ping制冰机控制板")
            Device.ping(Proto.ID_ICE)

            dialog.setMsg("ping珍珠架控制板")
            Device.ping(Proto.ID_PEARL)

            dialog.setMsg("ping粉料架控制板")
            Device.ping(Proto.ID_POWDER)

            dialog.setMsg("ping加热控制板")
            Device.ping(Proto.ID_HEAT)

            dialog.success("ping所有控制板成功")
        } catch (e: Exception) {
            e.printStackTrace()
            dialog.showError("ping所有", e)
        }
    }

    private suspend fun pingAny(name: String, dest: Int) {
        val dialog = showProg(name, "ping${name}")
        try {
            Device.ping(dest)
            dialog.success("ping${name}成功")
        } catch (e: Exception) {
            e.printStackTrace()
            dialog.showError(name, e)
        }
    }
}

